package org.robot.scm.platform.server.handler;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.robot.scm.platform.AbstractMonitor;
import org.robot.scm.platform.wxrobot.processor.VerifyRobotProcessor;
import org.robot.scm.pojos.TargetNotify;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.utils.JsonHelper;

/**
 * 发送授权码
 */
@Slf4j
@NoArgsConstructor
public class SendCodeHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/sendCode";
    }

    @Override
    public boolean needAuth() {
        return Boolean.FALSE;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        if (!exchange.getRequestMethod().equalsIgnoreCase("POST")) {
            sendFailureResponse(exchange, "请求非法");
            return;
        }
        BaseConfig baseConfig = new BaseConfig();
        baseConfig.setMainConfig(AbstractMonitor.mainConfig);
        String sendTo = config(PlatformEnum.VERIFY).get().getPushme(PlatformEnum.VERIFY).get(0);
        List<TargetNotify> notifies = new VerifyRobotProcessor().process(baseConfig, sendTo, "");
        String code = Optional.ofNullable(notifies.get(0)).map(TargetNotify::getDeviceSn).orElse("");
        sendSuccessResponse(exchange, "发送成功", code);
    }

}
